package com.id.coinscleaner.widget

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.id.coinscleaner.R
import com.id.coinscleaner.ktx.dp

class ScanProgressView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
    View(context, attrs, defStyleAttr) {
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    private val bgPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val fgPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private var pWidth: Float
    private val space = 1f.dp
    private var radius: Float

    private var ov: ValueAnimator? = null

    private var currentProgress = 0f

    init {
        val ta = context.obtainStyledAttributes(attrs, R.styleable.ScanProgressView)

        bgPaint.color = ta.getColor(R.styleable.ScanProgressView_backgroundColor, Color.parseColor("#C4C4C4"))
        fgPaint.color = ta.getColor(R.styleable.ScanProgressView_foregroundColor, Color.parseColor("#11A505"))

        pWidth = ta.getDimension(R.styleable.ScanProgressView_progressWidth, 14f.dp)

        radius = ta.getDimension(R.styleable.ScanProgressView_radius, 16f.dp)

        ta.recycle()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        ov?.cancel()
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        if (canvas == null) return

        val w = width.toFloat()
        val h = height.toFloat()

        canvas.drawRoundRect(0f, 0f, w, h, radius, radius, bgPaint)

        var left = radius / 2//左边预留的位置
        if (currentProgress < left) return

        val count = ((w - radius) / (pWidth + space)).toInt()//算出需要画多少个小圆
        val actualSpace = (w - radius - pWidth * count) / (count - 1)//实时计算的每个小方格空间

        for (i in 0 until count) {
            var right = pWidth + left
            var isBreak = false
            if (right >= currentProgress) {
                right = currentProgress
                isBreak = true
            }
            canvas.drawRoundRect(left, 1f.dp, right, h - 1f.dp, 4f.dp, 4f.dp, fgPaint)
            left = actualSpace + right
            if (isBreak) break
        }
    }

    fun startAnimate(duration: Long, updateListener: ((Float) -> Unit)? = null) {
        post {
            ov?.cancel()
            ov = ValueAnimator.ofInt(width)
            ov!!.duration = duration
            ov!!.addUpdateListener {
                setProgress(it.animatedFraction)
                updateListener?.invoke(currentProgress / width.toFloat())
            }
            ov!!.start()
        }
    }


    fun setProgress(fraction: Float) {
        currentProgress = fraction * width
        invalidate()//重绘，只绘制那些需要重绘的
    }


}